<template>
  <BasicModal
    v-bind="$attrs"
    title="异常"
    :width="modalWidth"
    @register="registerModal"
    :showOkBtn="false"
  >
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: t('sys.device.columns.valueXui'),
                tooltip: '下载布局异常',
                onClick: handleDownload.bind(null, record, 'html'),
              },
              {
                label: t('sys.device.columns.valuePng'),
                tooltip: '下载截图异常',
                onClick: handleDownload.bind(null, record, 'img'),
              },
              {
                label: t('sys.device.columns.log'),
                tooltip: '错误日志',
                onClick: handleDownload.bind(null, record, 'error'),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { getErrorApi } from '@/api/demo/device';
  import { columnsError } from './account.data';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const modalWidth = ref('80%'); // 可以是像 600 这样的像素值，或者百分比 '50%'
  const tableData = ref([]); // 定义一个响应式变量来存储表格数据
  const emit = defineEmits(['success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    const record = data.record; // 从 data 中获取 record 对象
    setModalProps({ confirmLoading: true }); // 显示加载状态
    try {
      const result = await getErrorApi(record.device);
      tableData.value = result.data; // 将接口返回的数据赋值给表格数据
    } catch (error) {
      console.error('Failed to fetch other versions:', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  });

  const [registerTable, { setTableData }] = useTable({
    dataSource: tableData,
    columns: columnsError,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 50,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
    },
  });

  async function handleDownload(record, type) {
    let urlpath = '';
    let filename = 'error';
    if (type === 'html') {
      urlpath = record.valueXui;
    } else if (type === 'img') {
      urlpath = record.valuePng;
      filename = 'error.png';
    } else if (type === 'error') {
      const errorText = record.type;
      const blob = new Blob([errorText], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'error.txt';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      return;
    }

    try {
      const response = await fetch(urlpath);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('下载文件时出错:', error);
    }
  }
</script>
